﻿using System.Reflection;
using System.Windows;
using System.Windows.Controls;

namespace LibrarySystem
{
    public class PasswordBoxHelper
    {


        public static string GetPwd(DependencyObject obj)
        {
            return (string)obj.GetValue(PwdProperty);
        }

        public static void SetPwd(DependencyObject obj, string value)
        {
            obj.SetValue(PwdProperty, value);
        }

        // Using a DependencyProperty as the backing store for Password.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty PwdProperty =
            DependencyProperty.RegisterAttached("Pwd", typeof(string), typeof(PasswordBoxHelper), new PropertyMetadata(string.Empty, (d, p) =>
            {
                var pwdBox = d as PasswordBox;
                if (pwdBox == null) return;
                pwdBox.Password = p.NewValue as string;
                if (string.IsNullOrEmpty(pwdBox.Password)) return;
                pwdBox?.GetType()?.GetMethod("Select", BindingFlags.Instance | BindingFlags.NonPublic)?.Invoke(pwdBox, new object[] { pwdBox.Password.Length, 0 });
            }));



        public static bool GetCanChangePassword(DependencyObject obj)
        {
            return (bool)obj.GetValue(CanChangePasswordProperty);
        }

        public static void SetCanChangePassword(DependencyObject obj, bool value)
        {
            obj.SetValue(CanChangePasswordProperty, value);
        }

        // Using a DependencyProperty as the backing store for CanChangePassword.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty CanChangePasswordProperty = 
            DependencyProperty.RegisterAttached("CanChangePassword", typeof(bool), typeof(PasswordBoxHelper), new PropertyMetadata(false, (DependencyObject d, DependencyPropertyChangedEventArgs p) =>
            {
                var pwdBox = d as PasswordBox;
                if (pwdBox == null) return;
                if ((bool)p.NewValue)
                {
                    pwdBox.PasswordChanged += (sender, args) =>
                    {
                        var box = sender as PasswordBox;
                        if (box == null) return;
                        SetPwd(box, box.Password);
                    };
                }
            }));
    }
}
